package com.valor.product.controller;

import com.valor.product.dataobject.ProductCategory;
import com.valor.product.dataobject.ProductInfo;
import com.valor.product.service.CategoryService;
import com.valor.product.service.ProductService;
import com.valor.product.utils.ResultVoUtil;
import com.valor.product.vo.ProductInfoVO;
import com.valor.product.vo.ProductVo;
import com.valor.product.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class ProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResultVO<ProductInfoVO> list(){
       List<ProductInfo> productInfos =  productService.findUpAll();
       List<Integer> categoryList = productInfos.stream().map(ProductInfo::getCategoryType)
                .collect(Collectors.toList());
       List<ProductCategory> productCategories =  categoryService.findByCategoryTypeIn(categoryList);

       List<ProductVo> productVoList = new ArrayList<>();
       for (ProductCategory productCategory:productCategories){
           ProductVo productVo = new ProductVo();
           productVo.setCategoryName(productCategory.getCategoryName());
           productVo.setCategoryType(productCategory.getCategoryType());

           List<ProductInfoVO> productInfoVOList = new ArrayList<>();
           for (ProductInfo productInfo:productInfos){
               if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
                   ProductInfoVO productInfoVO = new ProductInfoVO();
                   BeanUtils.copyProperties(productInfo, productInfoVO);
                   productInfoVOList.add(productInfoVO);
               }
           }
           productVo.setProductInfoVOList(productInfoVOList);
           productVoList.add(productVo);
       }

       return ResultVoUtil.success(productVoList);
    }
}
